package com.zb;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池运行时状态工具类
 */
@Component
public class ThreadPoolStatusMonitor {

    // 注入线程池工厂（用于获取已创建的线程池）
    private final ThreadPoolFactory threadPoolFactory;

    @Autowired
    public ThreadPoolStatusMonitor(ThreadPoolFactory threadPoolFactory) {
        this.threadPoolFactory = threadPoolFactory;
    }

    /**
     * 获取线程池的运行时参数
     * @param threadPoolName 线程池名称
     * @return 运行时参数（核心线程数、最大线程数等）
     */
    public Map<String, Object> getThreadPoolRuntimeStatus(String threadPoolName) {
        Map<String, Object> status = new ConcurrentHashMap<>();
        // 获取线程池实例（若未创建则返回空）
        ExecutorService executor = threadPoolFactory.build(threadPoolName);
        if (!(executor instanceof ThreadPoolExecutor)) {
            status.put("error", "线程池不存在或类型不匹配");
            return status;
        }

        ThreadPoolExecutor threadPool = (ThreadPoolExecutor) executor;
        // 线程池运行时参数
        status.put("threadPoolName", threadPoolName);
        status.put("corePoolSize", threadPool.getCorePoolSize());       // 实际核心线程数
        status.put("maximumPoolSize", threadPool.getMaximumPoolSize()); // 实际最大线程数
        status.put("activeCount", threadPool.getActiveCount());         // 活跃线程数
        status.put("queueSize", threadPool.getQueue().size());          // 队列当前任务数
        status.put("completedTaskCount", threadPool.getCompletedTaskCount()); // 已完成任务数
        status.put("keepAliveTime", threadPool.getKeepAliveTime(java.util.concurrent.TimeUnit.SECONDS)); // 空闲时间
        return status;
    }
}